import { PlusOutlined } from '@ant-design/icons';
import { useUpdateEffect } from 'ahooks';
import { Button, Drawer, Input, Layout, message, Modal, Space, Dropdown, MenuProps } from 'antd';
import { Content, Header } from 'antd/es/layout/layout';
import Sider from 'antd/es/layout/Sider';
import { useEffect, useRef, useState } from 'react';
import { TreeData } from '@/types/dataset';
import datasetService from '@/api/services/datasetService';
import { DatasetListItem, DatasetTypeEnum } from '@/common';
import { SvgIcon } from '@/components/icon';
import Back from '@/components/router/Back';
import useInitialize from '@/hooks/event/use-initialize';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useRouter, useParams } from '@/router/hooks';
import { useUserInfo } from '@/store/userStore';
import { isValidURL } from '@/utils/common';

import ApiDetail from './components/api-detail';
import ApiManageContextProvider, { ApiManageContext } from './context';
import { useManagePage } from '@/store/configStore';
import { useDatasetStore } from '@/store/datasetStore';
import './styles/api.scss';
import { useContextSelector } from 'use-context-selector';
import { ApiDatasetEvent } from '@/types/api';
import { ItemType } from 'antd/es/breadcrumb/Breadcrumb';
import BreadCrumb from './components/BreadCrumb';
import { transformToTreeItems } from '@/utils/tree';
import Modals from '@/components/modals/Modals';
import PagesHeader from '@/components/pages-header';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { UserRoleEnum } from '@/common/app/constants';
import DatasetHeader from './components/DatasetHeader';
import { useSize } from 'ahooks';
import TipDesc from '@/components/tipDesc/tipDesc';

interface ApiManageProps {
  appType?: string;
}

function ApiManage({ appType }: ApiManageProps) {
  const { loadAllDatasets1, getRolesList, rolesList } = useDatasetStore();
  const { appId = '' } = useParams() as { appId: string };
  const router = useRouter();
  const { homePage } = useInitialize();
  const [containerHeight, setContainerHeight] = useState(800);
  const [containerWidth, setContainerWidth] = useState(300);
  const [datasets, setDatasets] = useState<DatasetListItem[]>([]);
  const [selectedDataset, setSelectedDataset] = useState<DatasetListItem | undefined>(undefined);
  const [mobileApiVisible, setMobileApiVisible] = useState(false);
  const [syncDataVisible, setSyncDataVisible] = useState(false);
  const [apiUrl, setApiUrl] = useState('');
  const { isPc } = useWindowWidth();
  const [isAdmin, setIsAdmin] = useState(true);
  const [isPermit, setIspermit] = useState(true);
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  // const { id } = useParams();
  const { role, groupId } = useUserInfo();
  const [isImporting, setIsImporting] = useState(false);
  const [crumbs, setCrumbs] = useState<ItemType[]>([]);
  const managePage = useManagePage();
  const { event$ } = useContextSelector(ApiManageContext, (s) => s);
  const [page, setPage] = useState(1);
  const [parentId, setParentId] = useState<string | null>('');
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [treeData, setTreeData] = useState([]);
  const [messageApi, contextHolder] = message.useMessage();
  const [managers, setManagers] = useState([]); //知识库管理员
  const [approves, setApproves] = useState([]); //知识库审批人
  const [searchValue, setSearchValue] = useState('');
  const { userRole } = useOrchestrationStore();
  const ref = useRef<HTMLDivElement>(null);
  const size = useSize(ref);
  const { setDeleteModalVisible, setNewApiModalVisible, setNewDatasetModalVisible } =
    useContextSelector(ApiManageContext, (s) => s);

  const handleNewDataset = () => {
    setNewDatasetModalVisible(true);
  };

  useEffect(() => {
    // role?.code && setIspermit(role?.code != 'student' && role?.code != 'anonymous');
    // role?.code && setIsAdmin(role?.code === 'admin' || role?.code?.includes('admin'));
    setIsAdmin(userRole == UserRoleEnum?.admin);
  }, [role]);

  //获取管理员权限信息
  const getRolesAllList = async () => {
    const res = await getRolesList(appId);
    res?.forEach((item) => {
      if (item.code === 'knowledge_manager') {
        setManagers(item?.target_users);
      }
      if (item.code === 'knowledge_reviewer') {
        setApproves(item?.target_users);
      }
    });
  };

  //获取选择知识库列表
  const getSelectKnowledgeBaseList = async () => {
    try {
      const res = await datasetService.knowledgeBaseSelect({
        id: groupId,
      });
      setTreeData(res);
    } catch (error) {
      message.error(error instanceof Error ? error.message : String(error));
    }
  };

  const getDatasets = async () => {
    setLoading(true);
    try {
      //获取知识库数据
      const res: any = await loadAllDatasets1({
        parentId: parentId,
        page: page,
        page_size: pageSize,
        offset: (page - 1) * pageSize,
        searchText: searchValue,
        groupId: groupId,
        isPage: true,
        app_id: appId, //必填
        dataset_type: 'function',
      });
      const datas = transformToTreeItems(res.list, undefined, true);

      // const datas = await datasetService.getDatasetList({
      //   type: DatasetTypeEnum.api,
      //   parentId: null,
      // });
      setDatasets(datas);
      setTotal(res.total);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };
  const handlePageChange = (page: number, pageSize: number) => {
    setPage(page);
    setPageSize(pageSize);
  };
  useEffect(() => {
    getDatasets();
  }, [page, pageSize, searchValue]);

  const handleItemClicked = (item: DatasetListItem | undefined) => {
    setSelectedDataset(item);
  };

  const closeSyncDataModal = () => {
    setSyncDataVisible(false);
    setApiUrl('');
  };

  const confirmImportApi = async () => {
    if (!isAdmin) {
      messageApi.error('没有操作权限！');
      return;
    }
    if (!apiUrl) {
      messageApi.warning('请输入同步地址！');
      return;
    }
    if (!isValidURL(apiUrl)) {
      messageApi.warning('请输入正确的同步地址！');
      return;
    }

    try {
      setIsImporting(true);
      await datasetService.createKnowledgeBase({
        type: DatasetTypeEnum.function,
        dataset_type: 'function',
        avatar: '/imgs/dataset/dataset.svg',
        name: apiUrl,
        intro: '',
        vectorModel: 'embedding-model',
        agentModel: 'vllm-chat-model',
        parentId: null,
        openapiUrl: apiUrl,
        app_id: appId, //必填
        groupId: groupId,
        assessor: approves.map((item) => item?.id),
        administrator: managers.map((item) => item?.id),
      });
      messageApi.success('同步成功');
      setSyncDataVisible(false);
      setSelectedDataset(undefined);
      getDatasets();
    } catch (error) {
      console.error(error);
    } finally {
      setIsImporting(false);
    }
  };

  useEffect(() => {
    if (selectedDataset) {
      setCrumbs([
        {
          title: selectedDataset.name,
          key: selectedDataset._id,
        },
      ]);
    } else {
      setCrumbs([]);
    }
  }, [selectedDataset]);

  useEffect(() => {
    setContainerHeight(window.innerHeight - 80);
    setContainerWidth(window.innerWidth - 130);
    getDatasets();
    getSelectKnowledgeBaseList();
    getRolesAllList();
  }, []);

  useUpdateEffect(() => {
    if (selectedDataset == undefined) {
      getDatasets();
    }
  }, [selectedDataset]);

  useEffect(() => {
    // if (!isPc) {
    //   setMobileApiVisible(selectedDataset != undefined);
    // }
  }, [selectedDataset]);

  event$?.useSubscription((val) => {
    if (val == ApiDatasetEvent.REFRESHDATASET) {
      getDatasets();
    }
  });

  return (
    <Layout className="h-full" style={{ background: '#fff' }}>
      {contextHolder}
      {/* <div className="flex flex-nowrap items-center justify-between px-2"> */}
      {/* <div className="flex w-full rounded-xl bg-[#F5F7FB]"> */}
      <PagesHeader styles={{ flexDirection: 'row', marginTop: '11px' }}>
        <BreadCrumb
          disable={false}
          crumbs={crumbs}
          selectedItem={selectedDataset}
          onItemClicked={handleItemClicked}
        />
      </PagesHeader>
      <TipDesc title="配置和管理API数据接口类型的知识库" className='ml-5 !mt-0 !mb-4' />
      {isAdmin && (
        <Space className={`ml-auto mr-5 absolute right-0 z-10 ${appType === 'workflow' ? 'top-[132px]' : 'top-[65px]'}`}>
          <>
            <Button
              type="text"
              style={{ border: '1px solid #1B6DFA' }}
              icon={<PlusOutlined />}
              onClick={() => {
                setApiUrl('');
                setSyncDataVisible(true);
              }}
            >
              同步数据接口
            </Button>
          </>
          <DatasetHeader
            selectedItem={selectedDataset}
            isAdmin={isAdmin}
            isPermit={isPermit}
            parentSize={size ?? { width: 0, height: 0 }}
            onDeleteClicked={() => {
              setDeleteModalVisible(true);
            }}
            onNewClicked={() => {
              setNewApiModalVisible(true);
            }}
            onNewDatasetClicked={handleNewDataset}
          />
        </Space>
      )}
      {/* </div> */}
      {/* </div> */}

      <Layout style={{ background: '#fff' }}>
        <Content
          className="relative rounded-xl"
          style={{
            // height: containerHeight,
            overflowY: 'auto',
            overflowX: 'hidden',
          }}
        >
          <ApiDetail
            loading={loading}
            datasets={datasets}
            groupId={groupId}
            managers={managers}
            approves={approves}
            isAdmin={isAdmin}
            isPermit={isPermit}
            selectedItem={selectedDataset}
            onItemClicked={handleItemClicked}
            total={total}
            pageSize={pageSize}
            page={page}
            searchValue={searchValue}
            setSearchValue={setSearchValue}
            handlePageChange={handlePageChange}
          />
        </Content>
      </Layout>

      <Modals
        title={'同步数据接口'}
        open={syncDataVisible}
        onCancel={closeSyncDataModal}
        okText={isImporting ? '正在导入...' : '确定'}
        cancelText="取消"
        maskClosable={false}
        centered
        onOk={confirmImportApi}
      // footer={
      //   <div style={{ textAlign: 'center' }}>
      //     <Space size={56}>
      //       <Button onClick={closeSyncDataModal}>取消</Button>
      //       <Button loading={isImporting} type="primary" onClick={confirmImportApi}>
      //         {isImporting ? '正在导入...' : '确定'}
      //       </Button>
      //     </Space>
      //   </div>
      // }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input
            allowClear
            placeholder="请输入同步地址"
            value={apiUrl}
            onChange={(e) => setApiUrl(e.target.value)}
          />
          {/* {isImporting && <LoadingOutlined className='ml-2'/>} */}
        </div>
      </Modals>

      <Drawer
        title={
          <span
            style={{
              fontSize: '20px',
              fontWeight: 500,
              color: '#474C5F',
            }}
          >
            数据接口列表
          </span>
        }
        open={mobileApiVisible}
        onClose={() => {
          setMobileApiVisible(false);
        }}
        width="100%"
        zIndex={100}
        closeIcon={<SvgIcon icon="ic-back" size={24} />}
        className="drawer"
      >
        <div className="mt-2 h-full">
          <ApiDetail
            loading={loading}
            datasets={datasets}
            groupId={groupId}
            managers={managers}
            approves={approves}
            isAdmin={isAdmin}
            isPermit={isPermit}
            selectedItem={selectedDataset}
            onItemClicked={handleItemClicked}
            total={total}
            pageSize={pageSize}
            page={page}
            searchValue={searchValue}
            setSearchValue={setSearchValue}
            handlePageChange={handlePageChange}
          />
        </div>
      </Drawer>
    </Layout>
  );
}

function RenderApiManage({ appType }: { appType?: string }) {
  return (
    <ApiManageContextProvider>
      <ApiManage appType={appType} />
    </ApiManageContextProvider>
  );
}

export default RenderApiManage;
